/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.file.storage;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.foreveross.bsl.file.storage.local.LocalFileStorageFactory;
import com.foreveross.bsl.file.storage.tfs.TfsFileStorageFactory;

/**
 * 重构了之前的代码（）
 * 
 * @author rening, Wangyi
 * @version v2.0
 * 
 * @date 2013-7-16
 * 
 */
public abstract class FileStorageFactory {

	private final static Logger log = LoggerFactory
			.getLogger(FileStorageFactory.class);

	public static final String TYPE_TFS = "tfs";
	public static final String TYPE_LOCAL = "local";

	private static final String DEFAULT_STRATEGY_FILE = "classpath:/filestorage/strategy.properties";
	private static volatile FileStorageFactory instance;
	private static final byte[] locker = {};

	protected FileStorageFactory() {
	};

	public static FileStorageFactory getInstance() {
		if (instance == null) {
			synchronized (locker) {
				if (instance == null) {
					instance = buildFileStorageFactory();
				}
			}
		}
		return instance;
	}

	private static FileStorageFactory buildFileStorageFactory() {
		ResourceLoader resLoader = new DefaultResourceLoader();
		Resource res = resLoader.getResource(DEFAULT_STRATEGY_FILE);
		FileStorageFactory result = null;
		if (res.exists()) {
			Properties props = new Properties();
			try {
				log.debug("load filestorage strategy config: {}", res.getURL());
				props.load(res.getInputStream());
				String type = props.getProperty("filestorage.type");
				if (!StringUtils.isEmpty(type)
						&& TYPE_TFS.equals(type.toLowerCase())) {
					result = new TfsFileStorageFactory();
				} else {
					result = new LocalFileStorageFactory();
				}
			} catch (IOException e) {
				result = new LocalFileStorageFactory();
				log.error(e.getMessage());
			}
		}
		log.debug("FileStorageFactory instance: {}", result);
		return result;
	}

	public abstract FileStorage getFileStorage();
}
